﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace UT3Bots.Communications
{
	internal class MessageEventArgs : EventArgs
	{
		private Message _message;
		
		#region Properties
		public Message Message
		{
			get { return this._message; }
		}
		#endregion

		public MessageEventArgs(Message Message)
		{
			this._message = Message;
		}
	}

	internal class MessageHandler2
	{
		private UT3Connection _connection;
		private Queue<Message> _messageQueue;

		internal event EventHandler<MessageEventArgs> OnEventReceived;


		#region Properties
		public UT3Connection Connection
		{
			get { return this._connection; }
		}
		public Queue<Message> MessageQueue
		{
			get { return this._messageQueue; }
		}
		#endregion

		//Constructor
		internal MessageHandler2(string Server, int Port)
		{
			this._messageQueue = new Queue<Message>();
			this._connection = new UT3Connection(Server, Port);

			this._connection.OnDataReceived += new EventHandler<TcpDataEventArgs>(DataReceived);
			this._connection.OnErrorOccurred += new EventHandler<TcpErrorEventArgs>(ErrorOccurred);
		}

		internal void Disconnect()
		{
			this._connection.Disconnect();
		}

		private void ErrorOccurred(object sender, TcpErrorEventArgs e)
		{
			this.Disconnect();
		}

		private void DataReceived(object sender, TcpDataEventArgs e)
		{
			List<Message> newMessages = Message.FromVisualizerData(System.Text.UTF8Encoding.UTF8.GetString(e.Data, 0, e.Data.Length));
			lock (this._messageQueue)
			{
				foreach (Message m in newMessages)
				{
                    //Trace.WriteLine(m.ToString());
					if (m.IsEvent && this.OnEventReceived != null)
					{
						OnEventReceived.Invoke(this, new MessageEventArgs(m));
					}
					else
					{
						this._messageQueue.Enqueue(m);
					}
				}
			}

			
		}
	}
}
